package com.ts.graphql.client;

import java.util.Map;

/**
 *
 * 单个 GraphQL 请求操作
 *
 * @author suyi
 */
public class GraphQlOperation {



    /**
     * 单个 GraphQL 请求单元模板
     * ${请求名称} : ${请求API名称} (${请求参数}) {
     *     ${要求返回的字段}
     * }
     */
    final static String SINGLE_GRAPH_REQUEST_TEMPLATE = "%s:%s%s { %s }";

    /**
     * 别名
     */
    private String alias;

    /**
     * 操作名称
     */
    private String operationName;

    /**
     * 请求参数
     */
    private String paramsString;

    /**
     * 要求返回的字段
     */
    private ReturnAttributesRoot returnFields;

    GraphQlOperation(String requestAlias, String requestName, String paramsString, ReturnAttributesRoot returnFields) {
        this.alias = requestAlias;
        this.operationName = requestName;
        this.paramsString = wrapParamsWithBracketIfNecessary(paramsString);
        this.returnFields = returnFields;
    }

    public GraphQlOperation(String requestAlias, String requestName, Object paramsObject, ReturnAttributesRoot returnFields) {
        this(requestAlias, requestName, GraphQlParamsConverter.objectToGraphQLParamsString(paramsObject), returnFields);
    }

    public GraphQlOperation(String requestAlias, String requestName, Map<String, Object> paramsMap, ReturnAttributesRoot returnFields) {
        this(requestAlias, requestName, GraphQlParamsConverter.mapToGraphQLParamsString(paramsMap), returnFields);
    }

    /**
     * 处理没有参数的特殊情况。没有参数则不用加括号
     */
    private String wrapParamsWithBracketIfNecessary(String paramsString) {
        if (paramsString.trim().isEmpty()) {
            return paramsString;
        }
        return "(" + paramsString + ")";
    }

    @Override
    public String toString() {
        return String.format(SINGLE_GRAPH_REQUEST_TEMPLATE, alias, operationName, paramsString, returnFields);
    }
}